package com.jsh.erp.service.crk;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.KucunMapper;
import com.jsh.erp.datasource.mappers.ShipuDayMapper;
import com.jsh.erp.datasource.mappers.ShipuMapper;
import com.jsh.erp.datasource.mappers.ShipuMapperEx;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShipuService {
    private Logger logger = LoggerFactory.getLogger(ShipuService.class);

    @Resource
    private KucunMapper kucunMapper;
    @Resource
    private ShipuMapper shipuMapper;
    @Resource
    private ShipuDayMapper shipuDayMapper;
    @Resource
    private ShipuMapperEx shipuMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;
    @Resource
    private KucunService kucunService;


    public Shipu getShipu(long id)throws Exception {
        Shipu result=null;
        try{
            result= shipuMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<Shipu> getShipuListByIds(String ids)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<Shipu> list = new ArrayList<>();
        try{
            ShipuExample example = new ShipuExample();
            example.createCriteria().andIdIn(idList);
            list = shipuMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Shipu> getShipu()throws Exception {
        ShipuExample example = new ShipuExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Shipu> list=null;
        try{
            list= shipuMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Shipu> select(String name, String type, String remark, int offset, int rows)throws Exception {
        List<Shipu> list=null;
        try{
            list= shipuMapperEx.selectByConditionShipu(name, type, remark, offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public Long countShipu(String name, String type, String remark)throws Exception {
        Long result=null;
        try{
            result= shipuMapperEx.countsByShipu(name, type, remark);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertShipu(JSONObject obj, HttpServletRequest request)throws Exception {
        Shipu inOutItem = JSONObject.parseObject(obj.toJSONString(), Shipu.class);
        int result=0;
        try{
            inOutItem.setEnabled(true);
            result= shipuMapper.insertSelective(inOutItem);
            logService.insertLog("食谱管理",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(inOutItem.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateShipu(JSONObject obj, HttpServletRequest request)throws Exception {
        Shipu inOutItem = JSONObject.parseObject(obj.toJSONString(), Shipu.class);
        int result=0;
        try{
            result= shipuMapper.updateByPrimaryKeySelective(inOutItem);
            logService.insertLog("食谱管理",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(inOutItem.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteShipu(Long id, HttpServletRequest request)throws Exception {
        return batchDeleteShipuByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteShipu(String ids, HttpServletRequest request)throws Exception {
        return batchDeleteShipuByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteShipuByIds(String ids)throws Exception {
        int result = 0;
        String [] idArray=ids.split(",");
        //校验通过执行删除操作
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<Shipu> list = getShipuListByIds(ids);
        for(Shipu inOutItem: list){
            sb.append("[").append(inOutItem.getName()).append("]");
        }
        logService.insertLog("食谱管理", sb.toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        User userInfo=userService.getCurrentUser();
        try{
            result= shipuMapperEx.batchDeleteShipuByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public int checkIsNameExist(Long id, String name)throws Exception {
        ShipuExample example = new ShipuExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Shipu> list = null;
        try{
            list= shipuMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }

        return list==null?0:list.size();
    }

    public List<Shipu> findBySelect()throws Exception {
        ShipuExample example = new ShipuExample();
        example.createCriteria().andEnabledEqualTo(true)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("sort asc, id desc");
        List<Shipu> list = null;
        try{
            list= shipuMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetStatus(Boolean status, String ids)throws Exception {
        logService.insertLog("食谱管理",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ENABLED).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        List<Long> inOutItemIds = StringUtil.strToLongList(ids);
        Shipu inOutItem = new Shipu();
        inOutItem.setEnabled(status);
        ShipuExample example = new ShipuExample();
        example.createCriteria().andIdIn(inOutItemIds);
        int result=0;
        try{
            result = shipuMapper.updateByExampleSelective(inOutItem, example);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addDayDetail(String info, String rows) throws Exception {
        ShipuDayHead head = JSONObject.parseObject(info, ShipuDayHead.class);
        List<ShipuDayItem> items = JSONArray.parseArray(rows, ShipuDayItem.class);
        if(head != null && StringUtils.isNotEmpty(head.getOperTime()) && !CollectionUtils.isEmpty(items)){
            List<ShipuDay> shipuDayList = Lists.newArrayList();
            items.forEach(item->{
                ShipuDay shipuDay = new ShipuDay();
                shipuDay.setDay(head.getOperTime());
                shipuDay.setShicai(item.getKucun());
                shipuDay.setShicaiAmount(item.getAmount());
                shipuDay.setType(item.getShipu().split("_")[0].trim());
                shipuDay.setName(item.getShipu().split("_")[1].trim());
                shipuDayList.add(shipuDay);
            });
            shipuDayMapper.batchInsert(shipuDayList);
            // 更新当前库存
            List<Kucun> kucunList = kucunService.getKucun();
            if(!CollectionUtils.isEmpty(kucunList)){
                kucunList.forEach(kucun->{
                    List<ShipuDay> subShipuDayList = shipuDayList.stream().filter(shipuDay -> shipuDay.getShicai().equalsIgnoreCase(kucun.getName())).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(subShipuDayList)){
                        BigDecimal amount = new BigDecimal(kucun.getAmount());
                        for (ShipuDay shipuDay : subShipuDayList) {
                            amount = amount.subtract(new BigDecimal(shipuDay.getShicaiAmount()));
                        }
                        kucun.setAmount(amount.toString());
                        kucunMapper.updateByPrimaryKey(kucun);
                    }
                });
            }
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void deleteDayDetail(String day) throws Exception {
        List<ShipuDay> dayList = shipuDayMapper.queryByDay(day);
        if(!CollectionUtils.isEmpty(dayList)){
            List<Kucun> kucunList = kucunService.getKucun();
            for (ShipuDay shipuDay : dayList) {
                List<Kucun> updateKucunList = kucunList.stream().filter(e->e.getName().equalsIgnoreCase(shipuDay.getShicai())).collect(Collectors.toList());
                for (Kucun kucun : updateKucunList) {
                    BigDecimal amount = new BigDecimal(kucun.getAmount());
                    amount = amount.add(new BigDecimal(shipuDay.getShicaiAmount()));
                    kucun.setAmount(amount.toString());

                    kucunService.updateKucun(kucun);
                }
                shipuDayMapper.deleteByDay(day);
            }
        }
    }

    public List<ShipuDay> getDayDetailList(String day)throws Exception {
        return shipuDayMapper.queryByDay(day);
    }

    public List<ShipuDay> queryShipuListByDay(String day)throws Exception {
        return shipuDayMapper.queryShipuListByDay(day);
    }

    public List<String> queryDayList()throws Exception {
        return shipuDayMapper.queryDayList();
    }

}
